import moment from 'moment';
import {commonLang} from '@inbiz/utils'
import {
  createInbizSchema,
  createBaseSchema,
  createValidatorSchema,
  createComponentStyleSchema,
  createDecoratorStyleSchema,
  createModelSchema,
  createComponentLayout,
  createControllerSchema,
} from '@inbiz/setters';
import { ConfigProvider, DatePicker } from '@inbiz/antd';
import { useForm } from '@formily/react';
import { getMessage } from '@inbiz/react';
import '../preview/web/style.less';

import { createBehavior, createResource, GlobalRegistry } from '@inbiz/core';
import { EformDateRangePicker } from './locale';

export const defaultProps = {
  format: 'YYYY-MM-DD',
  dateQuickChoose: true,
  startPlaceholder: 'EformDateRangePicker.startPlaceholder',
  endPlaceholder: 'EformDateRangePicker.endPlaceholder',
  startDefaultValueType: 'variableDefaultValue',
  startCustomDefaultValue: null,
  startVariableDefaultValue: 'nowTime',
  endDefaultValueType: 'variableDefaultValue',
  endCustomDefaultValue: null,
  endVariableDefaultValue: 'nowTime',
  allowBeforeNow: true,
  allowClear: true,
  min: undefined,
  max: undefined,
};

export const propsSchema = createInbizSchema({
  attribute: {
    ...createBaseSchema({
      format: {
        type: 'string',
        enum: [
          'YYYY',
          'YYYYMMDD',
          'YYYY-MM',
          'YYYY-MM-DD',
          'YYYY-MM-DD HH:mm',
          'YYYY-MM-DD HH:mm:ss',
          'YYYY/MM/DD',
          'YYYY/MM/DD HH:mm',
          'YYYY/MM/DD HH:mm:ss',
          'DD-MM-YYYY',
          'DD-MM-YYYY HH:mm',
          'DD-MM-YYYY HH:mm:ss',
          'DD/MM/YYYY',
          'DD/MM/YYYY HH:mm',
          'DD/MM/YYYY HH:mm:ss',
        ],
        'x-decorator': 'FormItem',
        'x-component': 'Select',
      },
      dateQuickChoose: {
        type: 'boolean',
        enum: [true, false],
        'x-decorator': 'FormItem',
        'x-component': 'Select',
      },
      startPlaceholder: {
        type: 'string',
        'x-decorator': 'FormItem',
        'x-component': 'MultilingualInput',
      },
      endPlaceholder: {
        type: 'string',
        'x-decorator': 'FormItem',
        'x-component': 'MultilingualInput',
      },
      startDefaultValueType: {
        type: 'string',
        enum: ['variableDefaultValue', 'customDefaultValue'],
        'x-decorator': 'FormItem',
        'x-component': 'Radio.Group',
      },
      startCustomDefaultValue: {
        type: 'date',
        'x-decorator': 'FormItem',
        'x-component-props': {
          format: defaultProps.format,
        },
        'x-component': (props: any) => {
          const format = props.format;
          const form = useForm();
          const onChange = (value: any) => {
            var formatValue;
            if (value) {
              if (format?.indexOf('s') != -1) {
                formatValue = moment(value).startOf('second');
              } else if (format?.indexOf('m') != -1) {
                formatValue = moment(value).startOf('minute');
              } else if (format?.indexOf('H') != -1) {
                formatValue = moment(value).startOf('hour');
              } else if (format?.indexOf('D') != -1) {
                formatValue = moment(value).startOf('day');
              } else if (format?.indexOf('M') != -1) {
                formatValue = moment(value).startOf('month');
              } else {
                formatValue = moment(value).startOf('year');
              }
            }
            props.onChange(
              formatValue ? new Date(formatValue as unknown as string).toString() : formatValue,
            );
          };
          const locale=commonLang[GlobalRegistry.getDesignerLanguage() as keyof typeof commonLang]
          return (
            <ConfigProvider locale={locale}>
              <DatePicker
                {...props}
                dropdownClassName="clearSpaceOccupation"
                inputReadOnly={true}
                value={props.value ? moment(new Date(props.value), format) : props.value}
                onChange={onChange}
                showTime={
                  format?.indexOf('s') != -1 ||
                  format?.indexOf('m') != -1 ||
                  format?.indexOf('H') != -1
                    ? { format: format?.split(' ')[1] }
                    : false
                }
                picker={format === 'YYYY' ? 'year' : format?.indexOf('D') != -1 ? 'date' : 'month'}
                placeholder={getMessage('EformDateRangePicker.pleaseChoseStartDate')}
                disabledDate={(current) => {
                  const endDefaultValueType = (
                    form.query(/endDefaultValueType$/).take()! as { value: string }
                  )?.value;
                  const endCustomDefaultValue = (
                    form.query(/endCustomDefaultValue$/).take()! as { value: string }
                  )?.value;
                  const endVariableDefaultValue = (
                    form.query(/endVariableDefaultValue$/).take()! as { value: string }
                  )?.value;
                  // 不能超过结束时间
                  var endTime = false;
                  if (
                    endDefaultValueType === 'customDefaultValue' &&
                    endCustomDefaultValue != undefined
                  ) {
                    //结束时间
                    endTime = current > moment(endCustomDefaultValue);
                  }
                  if (endDefaultValueType === 'variableDefaultValue') {
                    if (endVariableDefaultValue === 'nowTime') {
                      //结束时间
                      if (format?.indexOf('s') != -1) {
                        endTime = current > moment().endOf('second');
                      } else if (format?.indexOf('m') != -1) {
                        endTime = current > moment().endOf('minute');
                      } else if (format?.indexOf('H') != -1) {
                        endTime = current > moment().endOf('hour');
                      } else if (format?.indexOf('D') != -1) {
                        endTime = current > moment().endOf('day');
                      } else if (format?.indexOf('M') != -1) {
                        endTime = current > moment().endOf('month');
                      }
                    }
                  }
                  return current && endTime;
                }}
              />
            </ConfigProvider>
          );
        },
        'x-reactions': {
          dependencies: [
            '.startDefaultValueType',
            '.format',
            '.endDefaultValueType',
            '.endVariableDefaultValue',
          ],
          fulfill: {
            schema: {
              'x-hidden': "{{$deps[0] !== 'customDefaultValue'}}",
              'x-component-props.format': '{{$deps[1]}}',
            },
            state: {
              value:
                "{{$deps[2] == 'variableDefaultValue' && $deps[3] == 'nowTime' ? (new Date($self.value) < new Date(new Date().toLocaleDateString() + ' 23:59:59') ? value : null) : value}}",
            },
          },
        },
      },
      startVariableDefaultValue: {
        type: 'string',
        enum: ['nowTime'],
        'x-decorator': 'FormItem',
        'x-component': 'Select',
        'x-reactions': {
          dependencies: ['.startDefaultValueType'],
          fulfill: {
            schema: {
              'x-hidden': "{{$deps[0] !== 'variableDefaultValue'}}",
            },
          },
        },
      },
      endDefaultValueType: {
        type: 'string',
        enum: ['variableDefaultValue', 'customDefaultValue'],
        'x-decorator': 'FormItem',
        'x-component': 'Radio.Group',
        // "x-reactions": {
        //   target: 'form.attribute.base.x-component-props.startCustomDefaultValue',
        //   effects: ['onFieldInputValueChange'],
        //   fulfill: {
        //     state: {
        //       value: null
        //     }
        //   }
        // }
      },
      endCustomDefaultValue: {
        type: 'date',
        'x-decorator': 'FormItem',
        'x-component-props': {
          format: defaultProps.format,
        },
        'x-component': (props: any) => {
          const format = props.format;
          const form = useForm();
          const onChange = (value: any) => {
            var formatValue;
            if (value) {
              if (format?.indexOf('s') != -1) {
                formatValue = moment(value).endOf('second');
              } else if (format?.indexOf('m') != -1) {
                formatValue = moment(value).endOf('minute');
              } else if (format?.indexOf('H') != -1) {
                formatValue = moment(value).endOf('hour');
              } else if (format?.indexOf('D') != -1) {
                formatValue = moment(value).endOf('day');
              } else if (format?.indexOf('M') != -1) {
                formatValue = moment(value).endOf('month');
              } else {
                formatValue = moment(value).endOf('year');
              }
            }
            props.onChange(
              formatValue ? new Date(formatValue as unknown as string).toString() : formatValue,
            );
          };
          const locale=commonLang[GlobalRegistry.getDesignerLanguage() as keyof typeof commonLang]
          return (
            <ConfigProvider locale={locale}>
              <DatePicker
                {...props}
                dropdownClassName="clearSpaceOccupation"
                inputReadOnly={true}
                value={props.value ? moment(new Date(props.value), format) : props.value}
                onChange={onChange}
                showTime={
                  format?.indexOf('s') != -1 ||
                  format?.indexOf('m') != -1 ||
                  format?.indexOf('H') != -1
                    ? { format: format?.split(' ')[1] }
                    : false
                }
                picker={format === 'YYYY' ? 'year' : format?.indexOf('D') != -1 ? 'date' : 'month'}
                placeholder={getMessage('EformDateRangePicker.pleaseChoseStartDate')}
                disabledDate={(current) => {
                  const startDefaultValueType = (
                    form.query(/startDefaultValueType$/).take()! as { value: string }
                  ).value;
                  const startCustomDefaultValue = (
                    form.query(/startCustomDefaultValue$/).take()! as { value: string }
                  ).value;
                  const startVariableDefaultValue = (
                    form.query(/startVariableDefaultValue$/).take()! as { value: string }
                  ).value;
                  // 不能小于开始时间
                  var startTime = false;
                  if (
                    startDefaultValueType === 'customDefaultValue' &&
                    startCustomDefaultValue != undefined
                  ) {
                    //开始时间
                    startTime = current < moment(startCustomDefaultValue);
                  }
                  if (startDefaultValueType === 'variableDefaultValue') {
                    if (startVariableDefaultValue === 'nowTime') {
                      //开始时间
                      if (format?.indexOf('s') != -1) {
                        startTime = current < moment().startOf('second');
                      } else if (format?.indexOf('m') != -1) {
                        startTime = current < moment().startOf('minute');
                      } else if (format?.indexOf('H') != -1) {
                        startTime = current < moment().startOf('hour');
                      } else if (format?.indexOf('D') != -1) {
                        startTime = current < moment().startOf('day');
                      } else if (format?.indexOf('M') != -1) {
                        startTime = current < moment().startOf('month');
                      }
                    }
                  }
                  return current && startTime;
                }}
              />
            </ConfigProvider>
          );
        },
        'x-reactions': {
          dependencies: [
            '.endDefaultValueType',
            '.format',
            '.startDefaultValueType',
            '.startVariableDefaultValue',
          ],
          fulfill: {
            schema: {
              'x-hidden': "{{$deps[0] !== 'customDefaultValue'}}",
              'x-component-props.format': '{{$deps[1]}}',
            },
            state: {
              value:
                "{{$deps[2] == 'variableDefaultValue' && $deps[3] == 'nowTime' ? (new Date($self.value) > new Date(new Date().toLocaleDateString()) ? value : null) : value}}",
            },
          },
        },
      },
      endVariableDefaultValue: {
        type: 'string',
        enum: ['nowTime'],
        'x-decorator': 'FormItem',
        'x-component': 'Select',
        'x-reactions': {
          dependencies: ['.endDefaultValueType'],
          fulfill: {
            schema: {
              'x-hidden': "{{$deps[0] !== 'variableDefaultValue'}}",
            },
          },
        },
      },
      allowBeforeNow: {
        type: 'boolean',
        'x-decorator': 'FormItem',
        'x-component': 'Switch',
      },
      allowClear: {
        type: 'boolean',
        'x-decorator': 'FormItem',
        'x-component': 'Switch',
      },
    }),
    ...createValidatorSchema(false, {
      'x-component-props': {
        type: 'object',
        properties: {
          min: {
            type: 'date',
            'x-decorator': 'FormItem',
            'x-component-props': {
              format: defaultProps.format,
            },
            'x-component': (props: any) => {
              const format = props.format;
              const onChange = (value: any) => {
                var formatValue;
                if (value) {
                  if (format?.indexOf('s') != -1) {
                    formatValue = moment(value).startOf('second');
                  } else if (format?.indexOf('m') != -1) {
                    formatValue = moment(value).startOf('minute');
                  } else if (format?.indexOf('H') != -1) {
                    formatValue = moment(value).startOf('hour');
                  } else if (format?.indexOf('D') != -1) {
                    formatValue = moment(value).startOf('day');
                  } else if (format?.indexOf('M') != -1) {
                    formatValue = moment(value).startOf('month');
                  } else {
                    formatValue = moment(value).startOf('year');
                  }
                }
                props.onChange(
                  formatValue ? new Date(formatValue as unknown as string).toString() : formatValue,
                );
              };
              // 控制最小值不能大于最大值（移除焦点，大于最大值，清空最小值）
              const handleBlur = () => {
                const max = props.max;

                // 是否大于最大值
                if (props.max && moment(props.value) > moment(max)) {
                  props.onChange(undefined);
                }
              };
              const locale=commonLang[GlobalRegistry.getDesignerLanguage() as keyof typeof commonLang]
              return (
                <ConfigProvider locale={locale}>
                  <DatePicker
                    {...props}
                    dropdownClassName="clearSpaceOccupation"
                    inputReadOnly={true}
                    placeholder={getMessage('EformDateRangePicker.pleaseChoseDate')}
                    value={props.value ? moment(props.value) : props.value}
                    onChange={onChange}
                    showTime={
                      format?.indexOf('s') != -1 ||
                      format?.indexOf('m') != -1 ||
                      format?.indexOf('H') != -1
                        ? { format: format?.split(' ')[1] }
                        : false
                    }
                    picker={
                      format === 'YYYY' ? 'year' : format?.indexOf('D') != -1 ? 'date' : 'month'
                    }
                    onBlur={handleBlur}
                  />
                </ConfigProvider>
              );
            },
            'x-reactions': {
              dependencies: ['.max', '.format'],
              fulfill: {
                schema: {
                  'x-component-props.max': '{{$deps[0]}}',
                  'x-component-props.format': '{{$deps[1]}}',
                },
              },
            },
          },
          max: {
            type: 'date',
            'x-decorator': 'FormItem',
            'x-component-props': {
              format: defaultProps.format,
            },
            'x-component': (props: any) => {
              const format = props.format;
              const onChange = (value: any) => {
                var formatValue;
                if (value) {
                  if (format?.indexOf('s') != -1) {
                    formatValue = moment(value).endOf('second');
                  } else if (format?.indexOf('m') != -1) {
                    formatValue = moment(value).endOf('minute');
                  } else if (format?.indexOf('H') != -1) {
                    formatValue = moment(value).endOf('hour');
                  } else if (format?.indexOf('D') != -1) {
                    formatValue = moment(value).endOf('day');
                  } else if (format?.indexOf('M') != -1) {
                    formatValue = moment(value).endOf('month');
                  } else {
                    formatValue = moment(value).endOf('year');
                  }
                }
                props.onChange(
                  formatValue ? new Date(formatValue as unknown as string).toString() : formatValue,
                );
              };
              // 控制最大值不能小于最小值（移除焦点，小于最小值，清空最大值）
              const handleBlur = () => {
                const min = new Date(props.min);
                // 是否小于最小值
                if (min && moment(props.value) < moment(min)) {
                  props.onChange(undefined);
                }
              };
              const locale=commonLang[GlobalRegistry.getDesignerLanguage() as keyof typeof commonLang]
              return (
                <ConfigProvider locale={locale}>
                  <DatePicker
                    {...props}
                    dropdownClassName="clearSpaceOccupation"
                    inputReadOnly={true}
                    placeholder={getMessage('EformDateRangePicker.pleaseChoseDate')}
                    value={props.value ? moment(props.value) : props.value}
                    onChange={onChange}
                    showTime={
                      format?.indexOf('s') != -1 ||
                      format?.indexOf('m') != -1 ||
                      format?.indexOf('H') != -1
                        ? { format: format?.split(' ')[1] }
                        : false
                    }
                    picker={
                      format === 'YYYY' ? 'year' : format?.indexOf('D') != -1 ? 'date' : 'month'
                    }
                    onBlur={handleBlur}
                  />
                </ConfigProvider>
              );
            },
            'x-reactions': {
              dependencies: ['.min', '.format'],
              fulfill: {
                schema: {
                  'x-component-props.min': '{{$deps[0]}}',
                  'x-component-props.format': '{{$deps[1]}}',
                },
              },
            },
          },
        },
      },
    }),
  },
  style: {
    ...createComponentStyleSchema(),
    ...createComponentLayout(),
    ...createDecoratorStyleSchema(),
  },
  senior: {
    ...createModelSchema(undefined, true),
    // ...createSoureSchema(),
  },
  controller: createControllerSchema({
    events: [{
      name:'onChange',
      label:'数据变更',
      platform:'web'
    },
    {
      name:'onOpenChange',
      label:'弹出/关闭日历',
      platform:'web'
    }
  ]
  })
});

export const Behavior = createBehavior({
  name: 'EformDateRangePicker',
  extends: ['Field'],
  selector: (node) => node.props?.['x-component'] === 'EformDateRangePicker',
  designerLocales: EformDateRangePicker,
  designerProps: { propsSchema, defaultProps },
});

export const Resource = createResource({
  icon: 'MoreTime',
  elements: [
    {
      componentName: 'Field',
      props: {
        type: 'array',
        title: {
          value: 'EformDateRangePicker.title',
          status: true,
        },
        'x-decorator': 'FormItem',
        'x-component': 'EformDateRangePicker',
        'x-component-props': defaultProps,
      },
    },
  ],
});
